# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2021/12/5 8:45
# @File           : file_manage.py
# @IDE            : PyCharm
# @desc           : 保存到本地
from application.settings import STATIC_ROOT, STATIC_URL
from fastapi import UploadFile
import sys
from utils.file.file_base import FileBase
from aiopathlib import AsyncPath


class FileManage(FileBase):
    """
    上传文件管理
    """

    def __init__(self, file: UploadFile, path: str):
        self.path = self.generate_static_file_path(path, file.filename)
        self.file = file

    async def async_save_local(self) -> dict:
        """
        保存文件到本地
        :return: 示例：
        {
            'local_path': 'D:\\project\\kinit_dev\\kinit-api\\static\\system\\20240301\\1709303205HuYB3mrC.png',
            'remote_path': '/media/system/20240301/1709303205HuYB3mrC.png'
        }
        """
        path = AsyncPath(self.path)
        if sys.platform == "win32":
            path = AsyncPath(self.path.replace("/", "\\"))
        if not await path.parent.exists():
            await path.parent.mkdir(parents=True, exist_ok=True)
        await path.write_bytes(await self.file.read())
        return {
            "local_path": str(path),
            "remote_path": str(STATIC_URL) + str(path).replace(str(STATIC_ROOT), '').replace("\\", '/'),
        }
